const fs= require('fs');
const EC= require('elliptic').ec;
const ec= new EC('secp256k1');

function getPub() {
    return generateKeys().getPublic('hex');
}
function generateKeys(){
    const fileName= './wallet.json'
    let res, keys;
    try{
        res= fs.readFileSync(fileName);
        res= JSON.parse(res)
        if(res.prv && res.pub) {
            keys= ec.keyFromPrivate(res.prv);
            if(keys.getPublic('hex')!== res.pub)
                keys= null;
        }
    }catch{
        keys= ec.genKeyPair();
        res= {
            prv: keys.getPrivate('hex'),
            pub: keys.getPublic('hex')
        };
        fs.writeFileSync(fileName, JSON.stringify(res));
        console.log('keys:', JSON.stringify(res))
    }
    if(keys)
        return keys;
    else{
        console.log('Invalid wallet');
    }
}

function sign({from, to, amount}){
    const keys= generateKeys();
    const buffer= Buffer.from(`${from}-${to}-${amount}`)
    return keys.sign(buffer).toDER('hex');
}
function verify({from, to, amount, sign}, pub){
    pub= ec.keyFromPublic(pub, 'hex');
    const keys=ec.keyFromPublic(pub)
    const buffer= Buffer.from(`${from}-${to}-${amount}`)
    return keys.verify(buffer, sign)
}

// trans1={from: 'zdt', to: 'lff', amount:100}
// trans2={from: 'zdt', to: 'lff', amount:10}
// trans1.sign= sign(trans1)
// console.log('sign1:', sign(trans1))
// verify1= verify(trans1, generateKeys().getPublic())
// console.log(verify1)
// console.log('pub:', getPub())

module.exports= {sign, verify, pub: getPub()};